from timeit import Timer

import sys
import math


def Problem():
    """The following iterative sequence is defined for the set of positive integers:

    n => n/2 (n is even)
    n => 3n + 1 (n is odd)
    
    Using the rule above and starting with 13, we generate the following sequence:
    13 => 40 => 20 => 10 => 5 => 16 => 8 => 4 => 2 => 1
    
    It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
    
    Which starting number, under one million, produces the longest chain?
    
    NOTE: Once the chain starts the terms are allowed to go above one million.
    """     
    
    L = []
    max_num, max_len = 0, 0
    for n in xrange((10**6)/2, 10**6):
        num, num_len = n, 0
        # loop until we finish
        while num != 1:
            #sequence conditions
            if num & 1 == 0:
                num /= 2
                # If its a number already calculated, we're done
                if num < len(L):
                    num_len += L[num] + 1
                    break
            else:
                num = 3*num + 1
            #increment chain count
            num_len += 1
            
        #max starting number
        if num_len > max_len:
            max_len = num_len
            max_num = n
        
    
    
            
 
    print "Answer for Problem 14 = %s (len = %s)" % (str(max_num),str(max_len))




    
if __name__ == "__main__":
    t = Timer(setup='from __main__ import Problem', stmt='Problem()').timeit(1)
    print "Execution time = %0.3f seconds" %(t,)